Synchronous TCP with Boost.Asio

Synchronous TCP(동기식 TCP)
Server
#define _CRT_SECURE_NO_WARNINGS
#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
using namespace std;
string make_daytime_string(void) {
time_t now = time(0);
return ctime(&now);
}
int main(void) {
try {
boost::asio::io_service io_service;
// 13
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));
while (1) {
tcp::socket socket(io_service);
acceptor.accept(socket);
//
string message = make_daytime_string();
boost::system::error_code ignored_error;
boost::asio::write(socket, boost::asio::buffer(message), ignored_error);
}
}
catch (exception& e) {
cerr << e.what() << '\n';
}
return 0;
}
80 port: http
13 port: datetime
Client
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
using namespace std;
int main() {
try {
boost::asio::io_service io_service;
// TCP Resolver
tcp::resolver resolver(io_service);
// ('127.0.0.1'), Daytime (13)
tcp::resolver::query query("localhost", "daytime");
// DNS IP .
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
//
tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
while (1) {
//
boost::array<char, 128> buf;
boost::system::error_code error;
// .
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof)
break;
else if (error)
throw boost::system::system_error(error);
//
cout.write(buf.data(), len);
}
}
catch (exception& e) {
cerr << e.what() << endl;
}
system("pause");
return 0;
}
boost asio를 이용하면 ws보다 훨씬 간결하게 코드를 작성할 수 있다.